<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <title>客服端</title>
</head>

<body style="overflow: hidden;">
<!--这里是HTML内容区-->

<div id="wrapBox">

</div>

<div id="btn" style="position: fixed;bottom: 100px; right: 10px;">
    <button id="scroll">开启滚动</button>
    <button id="stop">停止滚动</button>
</div>

<script src="jquery.min.js"></script>
<script src="socket.io.js"></script>
<script>
    var deBug   = true;
    var socket  = null;
    var connectType = 'socketIo'; //链接模式：webSocket; socketIo

    var socketIoUrlService  = "https://ws.mb928.com:4430/operator";
    //var webSocketUrlService = 'ws://192.168.10.31:18072';

    var isPing   = false; //是否开启心跳
    var pingTime = 10000; //发送心跳时间 10 秒

    var setIntervalId  = 0;//定时器id
    var setIntervalId1 = 0;//定时器id
    var setIntervalId2 = 0;//定时器id

	
	
    //var node_id = 1064992;
    //var account = 'robot1';
    //var password = 'e10adc3949ba59abbe56e057f20f883e';
	
	
	//请求参数
    var param = getRequest();

    var node_id        = parseInt(param.node_id);
	var account        = param.account;
	var password       = param.password;
	
	
	

    var token   = 0;
    var uin = 0;
    var session_id = 0;

    var room_id = 0;
    var client_third_party_id = 0;

    //var start_client_third_party_id = 2200000;//起始的第三方ID
    var scrollTrue = true;//屏幕是否滚动

    //页面初始化，加载入口
    window.onload = function() {
        //请求服务
        if(connectType == 'webSocket'){
            connectWebSocket();
        } else {
            connectSocketIo();
        }

        $("#wrapBox").css({"height":$(window).height()-200, "overflow-y":"auto"});
        //滚动
        $(document).on("click", "#scroll", function(){
            scrollTrue = true;
        });
        //停止滚动
        $(document).on("click", "#stop", function(){
            scrollTrue = false;
        });

    };

    //链接 socketIo
    var connectSocketIo = function () {
        deBugLog('socketIo模式');
        if (socket != null) {
            return ;
        }

        socket = io(socketIoUrlService);

        //连接成功事件
        socket.on('connect', function () {
            deBugLog('connected 链接成功');
            //发送登陆请求
            var requestParam = '{"cmd": "cmd_operator_login_req", "node_id":'+node_id+', "account":"'+account+'", "password":"'+password+'" }';
            sendMsgToService(requestParam, '-----发送登陆请求：');

            //十秒发送一次心跳
            if(isPing == true){
                if(setIntervalId > 0){
                    clearInterval(setIntervalId);
                }

                setIntervalId = setInterval(function(){
                    var requestParam = '{"cmd": "cmd_operator_ping_req", "uin": '+uin+', "node_id":'+node_id+', "session_id":'+session_id+' }';
                    sendMsgToService(requestParam, '-----发送心跳：');
                }, pingTime);
            }

            if(setIntervalId1 > 0){
                clearInterval(setIntervalId1);
            }
            if(setIntervalId2 > 0){
                clearInterval(setIntervalId2);
            }
            //启动定时，10秒请求一次待接待房间，并接待
            setIntervalId1 = setInterval(function(){
                getWaitingRoom();
            }, 15000);
            //启动定时，10秒请求一次接待中房间，并回复消息
            setIntervalId2 = setInterval(function(){
                getReceivingRoom();
            }, 10000);

            return ;
        });

        //收到服务器消息响应事件
        socket.on('server_reply_event', function (obj) {
            handleRsp(obj);

            return ;
        });
    };

    //连接webSocket
    var connectWebSocket = function() {
        deBugLog('webSocket模式');
        if (socket != null) {
            return ;
        }

        if ('WebSocket' in window) {
            socket = new WebSocket(webSocketUrlService);
        } else if ('MozWebSocket' in window) {
            socket = new MozWebSocket(webSocketUrlService);
        } else {
            alert('您的浏览器不支持WebSocket')
            return ;
        }

        //链接成功
        socket.onopen = function() {
            deBugLog('connected 链接成功');
            //发送登陆请求
            var requestParam = '{"cmd": "cmd_operator_login_req", "node_id":'+node_id+', "account":"'+account+'", "password":"'+password+'" }';
            sendMsgToService(requestParam, '-----发送登陆请求：');

            //十秒发送一次心跳
            if(isPing == true){
                if(setIntervalId > 0){
                    clearInterval(setIntervalId);
                }

                setIntervalId = setInterval(function(){
                    var requestParam = '{"cmd": "cmd_operator_ping_req", "uin": '+uin+', "node_id":'+node_id+', "session_id":'+session_id+' }';
                    sendMsgToService(requestParam, '-----发送心跳：');
                }, pingTime);
            }

            if(setIntervalId1 > 0){
                clearInterval(setIntervalId1);
            }
            if(setIntervalId2 > 0){
                clearInterval(setIntervalId2);
            }
            //启动定时，10秒请求一次待接待房间，并接待
            setIntervalId1 = setInterval(function(){
                getWaitingRoom();
            }, 15000);
            //启动定时，10秒请求一次接待中房间，并回复消息
            setIntervalId2 = setInterval(function(){
                getReceivingRoom();
            }, 10000);

            return ;
        };

        //收到消息
        socket.onmessage = function(e) {
            var obj = JSON.parse(e.data);//解析字符串为JSON对象
            handleRsp(obj);

            return ;
        };
    };

    //处理消息响应
    var handleRsp = function (obj) {
        deBugLog('收到消息-----');
        deBugLog(obj);

        if (obj.header.error_code != 0){
            return ;
        }

        //登陆响应
        if (obj.header.cmd == 'cmd_operator_login_rsp'){
            printScreen('客服：“'+obj.data.nick_name+'” 登陆：uin：'+obj.data.uin+'<br><br>');
            uin        = obj.data.uin;
            session_id = obj.data.session_id;
            token      = obj.data.token;

            return ;
        }

        //待接待房间获取响应。有则接待房间
        if (obj.header.cmd == 'cmd_operator_pull_wait_receive_room_list_rsp'){
            var tmpArr    = obj.data.msg;
            var tmpLength = obj.data.msg.length;
            if(obj.data.msg.length > 0){
                for(var i = 0; i < tmpLength; i++) {
                    // 接待客户
                    var requestParam = '{"cmd": "cmd_operator_receive_client_req", "node_id":'+node_id+', "client_third_party_id": '+tmpArr[i].client_third_party_id+', "room_id":'+tmpArr[i].room_id+', "uin":'+uin+', "session_id":'+session_id+' }';
                    sendMsgToService(requestParam, '-----接待客户：');
                }
            }

            return ;
        }

        //接待中房间获取响应。有则回复消息
        if (obj.header.cmd == 'cmd_operator_pull_receiving_room_list_rsp'){
            var tmpArr    = obj.data.msg;
            var tmpLength = obj.data.msg.length;
            if(obj.data.msg.length > 0){
                for(var i = 0; i < tmpLength; i++) {
                    //回复一条消息
                    var requestParam = '{ "cmd": "cmd_operator_send_msg_req", "client_third_party_id": '+tmpArr[i].client_third_party_id+', "node_id":'+node_id+', "uin":'+uin+', "session_id":'+session_id+', "room_id":'+tmpArr[i].room_id+', "msg":[{"content_type":"text", "text":"你好！！"}] }';
                    sendMsgToService(requestParam, '-----客服回复一条消息：');

                    printScreen('回复一条消息：你好！！房间号：'+tmpArr[i].room_id+'<br>');
                }
            }
            return ;
        }

        //房间简要信息
        if (obj.header.cmd == 'cmd_operator_has_room_brief_change_push'){
            if(obj.data.op_type == 1 && obj.data.receive_type == 1 && obj.data.room_id){
                //有待接待请求，立即接待
                printScreen(obj.data.client_third_party_id+'：请求客服，房间号：'+obj.data.room_id+'<br>');
                room_id = obj.data.room_id;
                client_third_party_id = obj.data.client_third_party_id;

                // if(client_third_party_id < start_client_third_party_id){
                //     return ;
                // }

                // 接待客户
                var requestParam = '{"cmd": "cmd_operator_receive_client_req", "node_id":'+node_id+', "client_third_party_id": '+client_third_party_id+', "room_id":'+room_id+', "uin":'+uin+', "session_id":'+session_id+' }';
                sendMsgToService(requestParam, '-----接待客户：');

            } else if(obj.data.op_type == 1 &&
                obj.data.receive_type == 2 &&
                obj.data.last_msg &&
                obj.data.last_msg.operator_uin == 0 &&
                obj.data.last_msg.data &&
                obj.data.last_msg.data[0] &&
                obj.data.last_msg.data[0].content_type &&
                obj.data.last_msg.data[0].content_type=='text'
            ){

                // if(client_third_party_id < start_client_third_party_id){
                //     return ;
                // }

                //收到客户普通消息
                var objMsg = obj.data.last_msg.data[0];
                printScreen('收到客户消息：'+objMsg.text+'<br>');

                //回复一条消息
                var requestParam = '{ "cmd": "cmd_operator_send_msg_req", "client_third_party_id": '+client_third_party_id+', "node_id":'+node_id+', "uin":'+uin+', "session_id":'+session_id+', "room_id":'+room_id+', "msg":[{"content_type":"text", "text":"你好！！"}] }';
                sendMsgToService(requestParam, '-----客服回复一条消息：');

                printScreen('回复一条消息：你好！！房间号：'+room_id+'<br>');
            }

            return ;
        }

        //接待客户返回
        if(obj.header.cmd == 'cmd_operator_receive_client_rsp'){
            printScreen('您接待了客户：'+obj.data.client_third_party_id+'，房间号：'+room_id+'<br>');
            return;
        }

        //客户结束对话
        if(obj.header.cmd == 'cmd_operator_has_client_end_service_push'){
            printScreen('客户：'+obj.data.client_third_party_id+'结束对话，房间号：'+room_id+'<br><br><br>');

            //参数重置
            room_id = 0;
            client_third_party_id = 0;

            return;
        }
    };




    /**
     * 获取待接待房间
     */
    var getWaitingRoom = function () {
        //回复一条消息
        var requestParam = '{ "cmd": "cmd_operator_pull_wait_receive_room_list_req", "node_id":'+node_id+', "uin":'+uin+', "session_id":'+session_id+' }';
        sendMsgToService(requestParam, '-----获取待接待房间：');
    };

    /**
     * 获取接待中房间
     */
    var getReceivingRoom = function () {
        //回复一条消息
        var requestParam = '{ "cmd": "cmd_operator_pull_receiving_room_list_req", "node_id":'+node_id+', "uin":'+uin+', "session_id":'+session_id+' }';
        sendMsgToService(requestParam, '-----获取接待中房间：');
    };

    /**
     * 向服务器发消息
     * @param msgStr    发送的json字符串
     * @param deBugStr  deBug提示文字
     */
    var sendMsgToService = function (msgStr, deBugStr) {
        if(socket == null){
            printScreen('链接已经断开');
            deBugLog('链接已经断开');
            return ;
        }

        deBugStr = deBugStr || '请求参数：';

        if(connectType == 'webSocket'){
            //webSocket模式，直接发送json字符串
            deBugLog(deBugStr + msgStr);
            socket.send(msgStr);
        } else {
            //socketIo模式，需要封装带上TOKEN，并将json字符串转为json对象发送
            var req = '{ "token":'+token+', "data":'+msgStr+' }';
            deBugLog(deBugStr + req);
            socket.emit('operator_event', JSON.parse(req));
        }
    };

    /**
     * 输出到屏幕
     * @param text
     */
    var printScreen = function (text) {
        $("#wrapBox").append(text);

        if(scrollTrue == true){
            document.getElementById("wrapBox").scrollTop = document.getElementById("wrapBox").scrollHeight;
        }
    };

    /**
     * 打印日志
     * @param msg
     */
    var deBugLog = function (msg) {
        if(deBug){
            console.log(msg);
        }
        return ;
    };
	
	/**
     * 获取URL参数
     * @returns {Object}
     */
    function getRequest () {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for(var i = 0; i < strs.length; i ++) {
                theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

</script>
</body>
</html>